#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "Connection.hpp"

using namespace log_ns;
const static int buffersize = 512;

class HandlerConnection
{
private:
    handler_t _process;

public:
    HandlerConnection(handler_t process) : _process(process) {}
    ~HandlerConnection() {}

    void HandlerRecver(Connection *conn)
    {
        errno = 0;
        // 1. 读取
        while (true)
        {
            char buffer[buffersize] = {0};
            ssize_t n = ::recv(conn->Sockfd(), buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                conn->AppendInbuffer(buffer);
            }
            else
            {
                if (errno == EWOULDBLOCK)
                {
                    break;
                }
                else if (errno == EINTR)
                {
                    continue;
                }
                else
                {
                    conn->_excepter(conn);
                    return;
                }
            }
        }

        // 2. 业务处理
        std::cout << "Inbuffer: " << conn->Inbuffer() << std::endl;
        _process(conn);
    }

    void HandlerSender(Connection *conn)
    {
        errno = 0;
        // 1. 直接写
        while (true)
        {
            ssize_t n = ::send(conn->Sockfd(), conn->Outbuffer().c_str(), conn->Outbuffer().size(), 0);
            if (n > 0)
            {
                conn->DiscardOutbuffer(n);
                if (conn->Outbuffer().empty())
                    break;
            }
            else if (n == 0)
            {
                break;
            }
            else
            {
                if (errno == EWOULDBLOCK)
                {
                    // 可能是条件不满足
                    break;
                }
                else if (errno == EINTR)
                {
                    continue;
                }
                else
                {
                    conn->_excepter(conn);
                    return;
                }
            }
        }
        // 2. 发送条件不满足，缓冲区还有数据
        if (!conn->Outbuffer().empty())
        {
            conn->_R->EnableConnection(conn->Sockfd(), true, true);
        }
        else
        {
            conn->_R->EnableConnection(conn->Sockfd(), true, false);
        }
    }

    void HandlerExcepter(Connection *conn)
    {
        conn->_R->DelConnection(conn->Sockfd());
    }
};